﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Net.Chirash.Twitter.TwitterDatabase;

namespace Net.Chirash.Twitter.TwitterClient.DBSyncronize
{
    public class CachingUpdateTaskObserver
        : IDisposable, Net.Chirash.Twitter.TwitterClient.DBSyncronize.ITaskObserver<System.Collections.Generic.IEnumerable<TwitterData>>
    {
        public TwitterCaching caching { get; private set; }
        public CachingUpdateTaskObserver(TwitterCaching caching)
        {
            this.caching = caching;
        }

        public void OnRefreshStart()
        {

        }

        public void OnRefreshEnd()
        {

        }

        public void OnCompleted()
        {
            this.Dispose(true);
        }

        public void OnError(Exception error)
        {

        }

        public void OnNext(IEnumerable<TwitterData> value)
        {
            foreach (var item in value)
            {
                if (item is Status)
                {
                    var sta = item as Status;
                    caching.UpdateStatuses(new Status[] { sta });
                }
                else if (item is DirectMessage)
                {
                    var dm = item as DirectMessage;
                    caching.UpdateDirectMessages(new DirectMessage[] { dm });
                }
                else if( item is DeletedData)
                {
                    var deldata  = item as DeletedData;
                    if (deldata.DeletedType == typeof(Status))
                    {
                        caching.DestroyStatus(deldata.ID);
                    }
                    else if (deldata.DeletedType == typeof(DirectMessage))
                    {
                        caching.DestroyDirectMessage(deldata.ID);
                    }
                }
            }
        }

        #region Dispose-Finalize Pattern

        private bool __disposed = false;
        public void Dispose()
        {
            GC.SuppressFinalize(this);
            this.Dispose(true);
        }

        protected void Dispose(bool disposing)
        {
            if (__disposed) return;
            if (disposing)
            {

            }

            this.caching.Dispose();

            //base.Dispose();
            __disposed = true;
        }

        ~CachingUpdateTaskObserver()
        {
            this.Dispose(false);
        }
        #endregion

    }
}
